package com.googlecode.perfectable.prosperable.entry;

import javax.servlet.http.HttpSession;

import com.googlecode.perfectable.eventable.routing.Channel;
import com.googlecode.perfectable.prosperable.message.ClientMessage;
import com.googlecode.perfectable.prosperable.message.ServerMessage;

public class ChannelManager {
	
	private static final String INBOUND_CHANNEL_ATTRIBUTE_NAME = "inboundChannel";
	private static final String OUTBOUND_CHANNEL_ATTRIBUTE_NAME = "outboundChannel";
	
	private static Channel<ClientMessage> createInboundChannel() {
		return Channel.create();
	}
	
	private static Channel<ServerMessage> createOutboundChannel() {
		return Channel.create();
	}
	
	public static Channel<ClientMessage> extractInbound(HttpSession session) {
		@SuppressWarnings("unchecked")
		Channel<ClientMessage> inboundChannel = (Channel<ClientMessage>) session
				.getAttribute(INBOUND_CHANNEL_ATTRIBUTE_NAME);
		if(inboundChannel == null) {
			inboundChannel = createInboundChannel();
			session.setAttribute(INBOUND_CHANNEL_ATTRIBUTE_NAME, inboundChannel);
		}
		return inboundChannel;
	}
	
	public static Channel<ServerMessage> extractOutbound(HttpSession session) {
		@SuppressWarnings("unchecked")
		Channel<ServerMessage> outboundChannel = (Channel<ServerMessage>) session
				.getAttribute(OUTBOUND_CHANNEL_ATTRIBUTE_NAME);
		if(outboundChannel == null) {
			outboundChannel = createOutboundChannel();
			session.setAttribute(OUTBOUND_CHANNEL_ATTRIBUTE_NAME, outboundChannel);
		}
		return outboundChannel;
	}
	
}
